package util;

import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import entity.SongInfo;
import util.baidu.BaiduMusicUtil;
import util.baidu.NetworkCaughtUtil;

public class MusicUtil {
	
	public static void main(String[] args) {
		//collectorMusicInfo(2, "1");
		System.out.println(getSongCount("1"));
	}
	
	private static NetworkCaughtUtil NET = new NetworkCaughtUtil();

	// 从百度音乐抓取音乐信息并存放到本地
	@SuppressWarnings("static-access")
	public static JSONArray collectorMusicInfo (Integer sum, String type) {
		JSONArray songList = new JSONArray();
		JSONObject baiduMusicList = BaiduMusicUtil.getMusicList(type, sum, 0);
		JSONArray musicList = baiduMusicList.getJSONArray("song_list");
		for (Object object : musicList) {
			JSONObject music = (JSONObject) object;
			SongInfo song = new SongInfo();
			song.setBaiduMusicId(music.getString("song_id"));
			song.setTitle(music.getString("title"));
			song.setAuthor(music.getString("author"));
			song.setCountry(music.getString("country"));
			song.setLanguage(music.getString("language"));
			song.setLrclink(music.getString("lrclink"));
			song.setStyle(music.getString("style"));
			song.setHot(music.getString("hot"));
			song.setPublishtime(music.getString("publishtime"));
			song.setType(type);
			
			NET.createURLConnection(music.getString("pic_big"));
			JSONObject path = NET.saveFileByURLConnection("/music/" + song.getTitle() , song.getTitle() + ".jpg");
			song.setPic_big(path.getString("relativePath"));
			song.setPic_small(path.getString("relativePath"));

			JSONObject songDetail = BaiduMusicUtil.getMusicDetail(song.getBaiduMusicId());
			NET.createURLConnection(songDetail.getJSONObject("bitrate").getString("file_link"));
			path = NET.saveFileByURLConnection("/music/" + song.getTitle());
			
			song.setFile_link(path.getString("relativePath"));
			SongInfo hql = new SongInfo();
			hql.setTitle(song.getTitle());
			@SuppressWarnings("unchecked")
			List<SongInfo> list = HibernateUtils.getByHql(HibernateUtils.createQueryHql(hql));
			if (list.size() > 0) {
				song.setId(list.get(0).getId());
				HibernateUtils.updateOne(song);
			}else {
				HibernateUtils.addOne(song);
			}
			songList.add(song);
		}
		return songList;
	}
	
	public static Integer getSongCount(String type) {
		String hql = "SELECT COUNT(id) FROM SongInfo WHERE type LIKE ?";
		Object[] params = {"%" + type + "%"};
		return Integer.parseInt(HibernateUtils.getOne(hql, params).toString());
	}
	
}
